/*
 * @Date: 2021-08-15 12:23:10
 * @information: 日记业务层
 */
import Util from '../utils/util'
import DiaryDao from '../dao/DiaryDao'

const diaryDao = new DiaryDao()


export default class DiaryService {
  async findAll (data) {
    const { page, size } = data
    const res = await diaryDao.findAll(data)
    const total = await diaryDao.getCount()
    // 实体转成普通对象
    // const r = res.map(el => el.get({ plain: true }))
    const model = {
      page,
      size,
      total,
      list: res,
    }
    return model
  }

  async findByUserId (data) {
    const { page, size, userId } = data
    const res = await diaryDao.findByUserId(data)
    const total = await diaryDao.getCount(userId)
    // 实体转成普通对象
    let list = res.map(el => el.get({ plain: true }))
    list = list.map(el => {
      el.username = el.userInfo.username
      Reflect.deleteProperty(el, 'userInfo')
      return el
    })
    const model = {
      page,
      size,
      total,
      list,
    }
    return model
  }

  async add (data) {
    const { content, userId } = data
    const obj = { content, userId }
    Util.delNotKey(obj)
    Util.checkObj(obj, ['content', 'userId'])
    const res = await diaryDao.add(obj)
    return res
  }

  async update (data) {
    const { id, content } = data
    const updatetime = Date.now()
    const res = await diaryDao.update({ updatetime, id, content })
    return res
  }

  async del (data) {
    const { id } = data
    const res = await diaryDao.del({ id })
    return res
  }



}


